<template>
  <view class="page">
    <!-- 页头导航 -->
    <view class="header-nav">
      <view class="nav-left" @tap="goBack">
        <image
          class="back-icon"
          src="/static/icons/left_arrow.png"
          mode="aspectFit"
        ></image>
      </view>
      <view class="nav-title">选择城市</view>
      <view class="nav-right">
        <button
          class="confirm-btn"
          @tap="handleConfirm"
          :disabled="!selectedCity"
        >
          确定
        </button>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="container">
      <!-- 热门城市 -->
      <view class="section">
        <view class="section-title">热门城市</view>
        <view class="hot-cities">
          <view
            v-for="city in hotCities"
            :key="city.id"
            class="city-item"
            :class="{
              'city-item-selected': selectedCity && selectedCity.id === city.id,
            }"
            @tap="selectCity(city)"
          >
            <text class="city-name">{{ city.name }}</text>
          </view>
        </view>
      </view>

      <!-- 按拼音分类的城市列表 -->
      <view class="section">
        <view class="section-title">全部城市</view>
        <view class="city-list">
          <view
            v-for="(cities, letter) in cityList"
            :key="letter"
            class="letter-group"
            :id="`letter-${letter}`"
          >
            <view class="letter-title">{{ letter }}</view>
            <view class="cities-in-letter">
              <view
                v-for="city in cities"
                :key="city.id"
                class="city-item"
                :class="{
                  'city-item-selected':
                    selectedCity && selectedCity.id === city.id,
                }"
                @tap="selectCity(city)"
              >
                <text class="city-name">{{ city.name }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 右侧拼音选择器 -->
    <view class="pinyin-selector">
      <view
        v-for="letter in pinyinLetters"
        :key="letter"
        class="pinyin-item"
        @tap="scrollToLetter(letter)"
      >
        <text class="pinyin-text">{{ letter }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getHotCitiesApi, getCityPinyinListApi } from "@/api/map.js";

// 数据
const hotCities = ref([]);
const cityList = ref({});
const selectedCity = ref(null);
const pinyinLetters = ref([]);

// 获取热门城市列表
const getHotCities = async () => {
  try {
    console.log("开始获取热门城市");
    const response = await getHotCitiesApi();
    console.log("热门城市响应:", response);
    hotCities.value = response;
  } catch (error) {
    console.error("获取热门城市失败:", error);
    uni.showToast({
      title: "获取热门城市失败",
      icon: "none",
    });
  }
};

// 获取按拼音分类的城市列表
const getCityList = async () => {
  try {
    console.log("开始获取城市列表");
    const response = await getCityPinyinListApi();
    console.log("城市列表响应:", response);

    if (response && typeof response === "object") {
      cityList.value = response;
      // 生成拼音字母列表
      pinyinLetters.value = Object.keys(response).sort();
    }
  } catch (error) {
    console.error("获取城市列表失败:", error);
    uni.showToast({
      title: "获取城市列表失败",
      icon: "none",
    });
  }
};

// 选择城市
const selectCity = (city) => {
  selectedCity.value = city;
  console.log("选择城市:", city);
};

// 确认选择
const handleConfirm = () => {
  if (selectedCity.value) {
    // 将选中的城市信息存储到本地存储，供上一页面使用
    uni.setStorageSync("selectedCity", selectedCity.value.name);

    // 使用uni.navigateBack返回，并通过events传递数据
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2]; // 上一个页面
    
    if (prevPage) {
      // 如果上一个页面有citySelected方法，则调用它
      // 通过事件总线传递
      uni.$emit("citySelected", { city: selectedCity.value.name });
    }

    uni.navigateBack();
  } else {
    uni.showToast({
      title: "请选择一个城市",
      icon: "none",
    });
  }
};

// 滚动到指定字母
const scrollToLetter = (letter) => {
  const element = document.getElementById(`letter-${letter}`);
  if (element) {
    element.scrollIntoView({
      behavior: "smooth",
      block: "start",
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 页面加载时获取数据
onMounted(() => {
  console.log("城市选择页面加载");

  // 获取当前选中的城市（如果有的话）
  const currentCity = uni.getStorageSync("currentCity");
  if (currentCity) {
    // 这里需要根据城市名称找到对应的城市对象
    // 由于我们还没有加载城市数据，先保存城市名称
    console.log("当前城市:", currentCity);
  }

  getHotCities();
  getCityList();
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #fff;
  overflow: hidden; /* 去掉滚动条 */
}

.container {
  padding: 20rpx;
  margin-top: 120rpx; /* 为固定的页头留出空间 */
  background-color: #fff;
  height: calc(100vh - 120rpx);
  overflow-y: auto;
  overflow-x: hidden;
  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 隐藏Webkit浏览器的滚动条 */
.container::-webkit-scrollbar {
  display: none;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 120rpx;
  height: 60rpx;
}

.confirm-btn {
  width: 120rpx;
  height: 60rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 28rpx;
  border: none;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.confirm-btn[disabled] {
  background-color: #c0c0c0;
  color: #fff;
}

.section {
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-left: 10rpx;
}

.hot-cities {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.hot-cities .city-item {
  width: calc((100% - 40rpx) / 3); /* 每行3个，减去2个gap的宽度 */
  min-width: 200rpx;
}

.city-item {
  padding: 30rpx 40rpx;
  background-color: #f0f0f0;
  border-radius: 12rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
  text-align: center;
  box-sizing: border-box;
}

.city-item-selected {
  background-color: #e6f3ff;
  border-color: #007aff;
}

.city-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.letter-group {
  margin-bottom: 30rpx;
}

.letter-title {
  font-size: 28rpx;
  color: #999;
  background-color: #f8f9fa;
  padding: 15rpx 20rpx;
  margin-bottom: 15rpx;
  border-radius: 6rpx;
}

.cities-in-letter {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.cities-in-letter .city-item {
  width: calc((100% - 40rpx) / 3); /* 每行3个，减去2个gap的宽度 */
  min-width: 200rpx;
  padding: 25rpx 35rpx;
}

.cities-in-letter .city-name {
  font-size: 30rpx;
}

/* 右侧拼音选择器样式 */
.pinyin-selector {
  position: fixed;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  z-index: 999;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.pinyin-item {
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.pinyin-item:active {
  background-color: rgba(0, 122, 255, 0.8);
  transform: scale(1.1);
}

.pinyin-text {
  font-size: 20rpx;
  color: #333;
  font-weight: bold;
}

.pinyin-item:active .pinyin-text {
  color: #fff;
}
</style>
